<?php

namespace app\api\controller;

use app\admin\model\Comment;
use app\admin\model\post\Post as PostPost;
use app\admin\model\post\Type;
use app\common\controller\Api;
use think\Db;
use think\Exception;

class Post extends Api
{
    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = ['*'];

    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = ['*'];
    /**
     * 帖子分类列表
     */
    public function getTypeList()
    {
        // $where = ['deletetime' => null, 'status' => 1];
        // $list = Type::where($where)->order('weigh desc, createtime desc')->field('id,name')->select();
        $list = [];
        $this->success('获取成功', $list);
    }
    /**
     * 获取帖子列表
     */
    public function getPostList()
    {
        $params = $this->request->param();
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        // 初始化查询条件
        $query = PostPost::where('deletetime', null)
            ->where('stutes', 1);

        // 添加 type_id 条件
        // if (isset($params['type_id']) && $params['type_id'] > 0) {
        //     $query->where('type_id', $params['type_id']);
        // }
        if (isset($params['province_city']) && $params['province_city'] > 1) { // 大于1,7,13 是为了全部
            if (isset($params['urban_city']) && $params['urban_city'] > 7) {
                if (isset($params['district_city']) && $params['district_city'] > 13) {
                    $query->where('province_city', $params['province_city'])
                        ->where('urban_city', $params['urban_city'])
                        ->where('district_city', $params['district_city']);
                } else {
                    $query->where('province_city', $params['province_city'])
                        ->where('urban_city', $params['urban_city']);
                }
            } else {
                $query->where('province_city', $params['province_city']);
            }
        }
        // 添加 name 模糊查询
        if (isset($params['keyword']) && $params['keyword'] != '') {
            $query->where('name', 'like', '%' . $params['keyword'] . '%');
        }

        $order = 'weigh desc, createtime desc';

        $list = $query->order($order)
            ->field('id,name,image')
            ->paginate(['list_rows' => $limit, 'page' => $page])
            ->each(function ($item) {
                $item['image'] = cdnurl($item['image'], true);
                return $item;
            });

        $this->success('获取成功', $list);
    }
    /**
     * 获取帖子详情
     */
    public function getPostDetail()
    {
        $user_id = $this->auth->id;
        // $user_id = 1;
        if (!$user_id) {
            $this->error('请先登录');
        }
        $params = $this->request->param();
        $id = $params['id'] ?? 0;
        if ($id <= 0) {
            $this->error('参数错误');
        }
        $post = PostPost::where('id', $id)->find();
        if (!$post) {
            $this->error('帖子不存在');
        }
        $post['wx_image'] = cdnurl($post['wx_image'], true);
        // $post['image'] = cdnurl($post['image'], true);
        $post['images'] = array_map(function ($v) {
            return cdnurl($v, true);
        }, explode(',', $post['images']));
        $post['createtime_text'] = date('Y-m-d H:i:s', $post['createtime']);
        $collect = Db::name('collect')->where('user_id', $user_id)->where('post_id', $id)->count();
        if ($collect) {
            $post['is_collect'] = 1;
        } else {
            $post['is_collect'] = 0;
        }
        $post['province_city_name'] = $this->getRegion($post['province_city']);
        $post['urban_city_name'] = $this->getRegion($post['urban_city']);
        $post['district_city_name'] = $this->getRegion($post['district_city']);
        $post['all_address'] = $post['province_city_name'] . $post['urban_city_name'] . $post['district_city_name'];
        // unset($post['province_city']);
        // unset($post['urban_city']);
        // unset($post['district_city']);
        unset($post['image']);
        unset($post['updatetime']);
        unset($post['deletetime']);
        unset($post['weigh']);
        // unset($post['type_id']);
        $this->success('获取成功', $post);
    }
    /**
     * 获取省市区姓名
     */
    public function getRegion($id = 0)
    {
        if ($id == 0) {
            return;
        }
        $name = Db::name('area')->where('id', $id)->value('name');
        return $name;
    }
    /**
     * 发布帖子
     */
    public function addPost()
    {
        $params = $this->request->param();
        $params['user_id'] = $this->auth->id;
        $params['id'] = $params['id'] ?? 0;
        if (!$params['user_id']) {
            $this->error('请先登录');
        }
        $stutes = Db::name('user')->where('id', $params['user_id'])->value('stutes');
        if ($stutes != 2) {
            $this->error('未认证用户无法发布帖子!');
        }
        // if (!isset($params['type_id']) || $params['type_id'] <= 0) {
        //     $this->error('请选择分类');
        // }
        if (!isset($params['name']) || $params['name'] == '') {
            $this->error('标题不能为空');
        }
        $params['content'] = $params['name'];
        if (!isset($params['content']) || $params['content'] == '') {
            $this->error('内容不能为空');
        } else {
            $res = checkText($params['content']);
            if ($res['Code'] == 0) {
                $this->error('标题含有违规内容，请重新编辑!');
            }
        }
        $user = Db::name('user')->where('id', $params['user_id'])->find();
        if ($user) {
            $params['mobile'] = $user['mobile_r'];
            $params['wx_image'] = $user['wx_image'];
            $params['province_city'] = $user['province_city'];
            $params['urban_city'] = $user['urban_city'];
            $params['district_city'] = $user['district_city'];
        }
        if (!isset($params['province_city']) || $params['province_city'] <= 0) {
            $this->error('请选择省市区');
        }
        if (!isset($params['urban_city']) || $params['urban_city'] <= 0) {
            $this->error('请选择城市');
        }
        if (!isset($params['district_city']) || $params['district_city'] <= 0) {
            $this->error('请选择区县');
        }
        if (!isset($params['mobile']) || $params['mobile'] == '') {
            $this->error('手机号不能为空');
        }
        if (!isset($params['wx_image']) || $params['wx_image'] == '') {
            $this->error('微信图片不能为空');
        }
        if (!isset($params['images']) || $params['images'] == '') {
            $this->error('图片不能为空');
        }
        $uwx_image = Db::name('user')->where('id', $params['user_id'])->value('wx_image');
        if ($uwx_image == '' || $uwx_image == null) {
            Db::name('user')->where('id', $params['user_id'])->update(['wx_image' => $params['wx_image']]);
        }
        $image = explode(',', $params['images'])[0];
        $optinos = [
            'auth_id' => $params['user_id'],
            'type_id' => 1,
            'province_city' => $params['province_city'],
            'urban_city' => $params['urban_city'],
            'district_city' => $params['district_city'],
            'name' => $params['name'],
            // 'content' => $params['content'],
            'content' => $params['name'],
            'mobile' => $params['mobile'],
            'wx_image' => $params['wx_image'],
            'image' => $image,
            'images' => $params['images'],
            'stutes' => '1',
            'reason' => '',
            'createtime' => time(),
            'updatetime' => time(),
            'weigh' => '0',
        ];
        if ($params['id'] > 0) {
            $optinos = [
                'auth_id' => $params['user_id'],
                'type_id' => 1,
                'province_city' => $params['province_city'],
                'urban_city' => $params['urban_city'],
                'district_city' => $params['district_city'],
                'name' => $params['name'],
                'content' => $params['content'],
                'mobile' => $params['mobile'],
                'wx_image' => $params['wx_image'],
                'image' => $image,
                'images' => $params['images'],
                'stutes' => '1',
                'reason' => '',
                'updatetime' => time(),
            ];
        }
        Db::startTrans();
        try {
            if ($params['id'] > 0) {
                $post = PostPost::where('id', $params['id'])->update($optinos);
            } else {
                $post = PostPost::create($optinos);  // 使用create方法更安全
            }
            Db::commit();
            $this->success('发布成功');  // 返回帖子ID
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage() . $e->getLine() . $e->getFile());
        }
    }
    /**
     * 帖子留言
     */
    public function addComment()
    {
        $user_id = $this->auth->id;
        // $user_id = 1;
        if (!$user_id) {
            $this->error('请先登录');
        }
        $params = $this->request->param();
        if (!isset($params['post_id']) || $params['post_id'] <= 0) {
            $this->error('参数错误');
        }
        if (!isset($params['content']) || $params['content'] == '') {
            $this->error('内容不能为空');
        }
        $options = [
            'user_id' => $user_id,
            'post_id' => $params['post_id'],
            'pid' => $params['pid'] ?? 0,
            'content' => $params['content'],
            'images' => $params['images'] ?? '',
            'createtime' => time(),
        ];
        Db::startTrans();
        try {
            $comment = Comment::create($options);
            if (!$comment) {
                throw new Exception('留言失败');
            }
            Db::commit();
            $this->success('留言成功', ['id' => $comment->id]);
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }
    /**
     * 根据用户获取帖子列表
     */
    public function getPostListByUser()
    {
        $user_id = $this->auth->id;
        // $user_id = 2;
        if (!$user_id) {
            $this->error('请先登录');
        }
        $params = $this->request->param();
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;
        $query = PostPost::where('auth_id', $user_id)
            ->where('deletetime', null);
        $order = 'weigh desc, createtime desc';
        $list = $query->order($order)
            ->field('id,name,image,stutes,reason')
            ->paginate(['list_rows' => $limit, 'page' => $page])
            ->each(function ($item) {
                $item['image'] = cdnurl($item['image'], true);
                return $item;
            });
        $this->success('获取成功', $list);
    }
    /**
     * 用户删除帖子
     */
    public function delPost()
    {
        $user_id = $this->auth->id;
        // $user_id = 2;
        if (!$user_id) {
            $this->error('请先登录');
        }
        $params = $this->request->param();
        $id = $params['id'] ?? 0;
        if ($id <= 0) {
            $this->error('参数错误');
        }
        $post = PostPost::where('id', $id)->where('auth_id', $user_id)->find();
        if (!$post) {
            $this->error('帖子不存在');
        }
        Db::startTrans();
        try {
            $row = $post->delete();
            if (!$row) {
                throw new Exception('删除失败');
            }
            Db::commit();
            $this->success('删除成功');
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }
}
